#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:sirian
# datetime:2018/11/7 21:07
# software: PyCharm

import time
import requests
from bs4 import BeautifulSoup

def captcha_write(captcha_data):
    with open('captcha.jpg', "wb") as f:
        f.write(captcha_data)
    captcha_text = raw_input("输入验证码：")
    return captcha_text

def salasolo_spider():

    #构建一个页面session，保存cookie
    sess = requests.Session()

    ua = {
        "Connection": "keep-alive",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Accept-Language": "zh-CN,zh;q=0.9",
    }

    # 首先获取登录页面，找到需要POST的数据，同时会记录当前网页的Cookie值
    html = sess.get("https://account.guokr.com/sign_in/",  headers=ua).text
    print(html)

    #xml解析
    content = BeautifulSoup(html, "lxml")

    #得到csrf_token和captcha_rand
    csrf_token = content.find("input", attrs={"name":"csrf_token"}).get("value")
    captcha_rand = content.find("input", attrs={"name": "captcha_rand"}).get("value")
    #print(csrf_token)


    #获取验证码的地址
    captcha_url = content.find("img", attrs={"id":"captchaImage"}).get("src")
    #获取验证码的码流
    captcha_data = sess.get(captcha_url, headers=ua).content
    captcha_text = captcha_write(captcha_data)

    post_data = {
        "csrf_token":csrf_token,
        'username':'15010093097',
        'password':"51969863ly",
        "captcha":captcha_text,
        "captcha_rand":captcha_rand,
        "permanent":"y"
    }

    # 发送登录需要的POST数据，获取登录后的Cookie(保存在sess里)
    response = sess.post("https://account.guokr.com/sign_in/", data = post_data, headers = ua)
    print(response.text)

if __name__ == "__main__":
    salasolo_spider()